package com.micro.magupe.auth.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.micro.magupe.auth.entity.Role;
import com.micro.magupe.auth.service.RoleService;
import com.micro.magupe.common.bean.Query;
import com.micro.magupe.common.bean.Result;
import com.micro.magupe.common.util.PageUtils;
import com.micro.magupe.common.vo.RoleVO;

@RequestMapping("/role")
@Controller
public class RoleController {

	@Autowired
	RoleService roleService;
	
	@ResponseBody
	@RequestMapping(value="/getById", method=RequestMethod.GET)
	RoleVO getById(@RequestParam String id) {
		RoleVO roleVO = roleService.getById(id);
		return roleVO;
	}
	
	@GetMapping("/list")
	@ResponseBody
	PageUtils list(@RequestParam Map<String, Object> params) {
		Query query = new Query(params);
		List<RoleVO> list = roleService.listQuery(query);
		
		int total = roleService.count(query);
		PageUtils pageUtil = new PageUtils(list, total);
		return pageUtil;
	}
	
	@PostMapping("/save")
	@ResponseBody
	Result save(RoleVO roleVO) {
		if (roleService.save(roleVO) > 0) {
			return Result.ok();
		}
		
		return Result.error();
	}
	
	@PostMapping("/update")
	@ResponseBody
	Result update(RoleVO roleVO) {
		if (roleService.update(roleVO) > 0) {
			return Result.ok();
		}
		
		return Result.error();
	}
	
	@GetMapping("/listRole")
	@ResponseBody
	List<RoleVO> listRole() {
		List<RoleVO> list = roleService.list(new Role());
		return list;
	}
	
	@ResponseBody
	@RequestMapping(value="/listByUserId", method=RequestMethod.GET)
	List<RoleVO> listByUserId(@RequestParam String userId) {
		return roleService.listByUserId(userId);
	}
	
	/**
	 * 返回所有角色列表并标注那个角色是当前用户
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/listByUserId2", method=RequestMethod.GET)
	List<RoleVO> listByUserId2(@RequestParam String userId) {
		List<RoleVO> listAll = roleService.list(new Role()); 
		List<RoleVO> list = roleService.listByUserId(userId);
		Set<String> ids = new HashSet<String>();	
		for (RoleVO roleVO : list) {
			ids.add(roleVO.getId());
		}
		
		for (RoleVO roleVO : listAll) {
			if(ids.contains(roleVO.getId())) {
				roleVO.setCheck(true);
			} else {
				roleVO.setCheck(false);
			}
		}
		
		return listAll;
	}
}
